from flask import request, jsonify, Blueprint, current_app as app, send_from_directory, make_response
import traceback
from libs import logerr_util
from libs.utils import get_file_extract
from applications.config import UPLOAD_PATH

util_logger = logerr_util.get_logger()
blueprint = Blueprint("api_common", __name__, url_prefix="/api/api_common")

# from flask_cors import CORS
# CORS(blueprint)


@blueprint.route("/test", methods=["GET"])
def test():
    res_dict = {
        "code": 20000,
        "msg": "success",
    }
    try:
        res_dict["data"] = [i for i in range(10)]
        return jsonify(res_dict)
    except Exception as e:
        res_dict["code"] = 50000
        res_dict["msg"] = e.args
        util_logger.error(traceback.format_exc())
        # print(traceback.format_exc())
    finally:
        return jsonify(res_dict)


ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'xlsx', 'gif', 'GIF', 'zip', 'rar'])


# 用于判断文件后缀
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


import os
import time


# 公用的文件上传
@blueprint.route("/upload", methods=['POST'])
def upload():
    res_dict = {
        "code": 20000,
        "msg": 1,
        "data": []
    }
    file_list = request.files
    res_path = []
    for item in file_list:
        file = request.files.get(item)
        if not file:
            continue
        filename_temp = str(int(time.time())) + "_" + file.filename
        filepath, shot_name, extension = get_file_extract(filename_temp)
        extension = extension.replace(".", "")
        if extension not in ALLOWED_EXTENSIONS:
            continue
        where = os.path.join(UPLOAD_PATH, filename_temp)
        file.save(where)
        temp_path = os.path.join("uploads", filename_temp)
        res_path.append(temp_path)
    res_dict["data"] = res_path
    return jsonify(res_dict)


# 公用文件预览,下载
@blueprint.route('/download', methods=['GET'])
def show_photo():
    filename = request.values.get('filename')
    as_attachment_bool = request.values.get('down', False)

    if as_attachment_bool:
        dir_path = os.path.join(UPLOAD_PATH)
        return send_from_directory(dir_path, filename,
                                   as_attachment=as_attachment_bool)  # as_attachment=True 一定要写，不然会变成打开，而不是下载
    else:
        file_dir = os.path.join(UPLOAD_PATH, filename)
        filepath, shot_name, extension = get_file_extract(file_dir)
        extension = extension.replace(".", "")
        image_data = open(file_dir, "rb").read()
        response = make_response(image_data)
        response.headers['Content-Type'] = 'image/png'
        return response
